package Demo06;

import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        System.out.println("程序开始执行");
    }

}

class MyTimerTask implements Comparable<MyTimerTask>{
    private long delay;
    private Runnable runnable;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.delay = delay + System.currentTimeMillis();
    }
    public long getDelay(){
        return delay;
    }
    public Runnable getRunnable() {
        return runnable;
    }
    @Override
    public int compareTo(MyTimerTask o2) {
        return (int) (this.delay - o2.delay);
    }
}

class MyTimer {
    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(() -> {
            while(true) {
                synchronized(locker) {
                    while(queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    MyTimerTask myTimerTask = queue.peek();
                    long nowTimes = System.currentTimeMillis();
                    if(myTimerTask.getDelay() <= nowTimes) {
                        myTimerTask.getRunnable().run();
                        queue.poll();
                    }else{
                        try {
                            locker.wait(myTimerTask.getDelay() - nowTimes);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long delay) {
        synchronized(locker){
            queue.offer(new MyTimerTask(runnable, delay));
            locker.notify();
        }

    }
}